<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018-12-25
 * Time: 14:31
 */

namespace app\api\controller;


use Alipay\Alipayobj;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\Deposit;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Controller;
use think\Db;
use Wechat\Wxobjopen;

class DepositPay extends Pub
{
    public function wxpay($param)
    {
        try {
            $r=$this->deposit_creat($param);
            if($r=="error"){
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '该房间未退房';
                return $rarr;
            }
            $map['id'] = $param['merchantid'];
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $sh = $param['merchantid'];
            $weObj = new Wxobjopen($options);
            //充值

            $zk_price = 0;

            $pay_fees = $param['total_fee'] - $zk_price;

            //END
            //支付金额保留两位小数
            $price = $this->format_price($pay_fees);
            //END
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $param['orderid'];
            $body = "快捷支付";
            $sub_mch_id = $config['sub_mch_id'];
            if ($userwx['authorizer_appid'] !== $appid) {
                $sub_appid = $userwx['authorizer_appid'];
            } else {
                $sub_appid = '';
            }
            $total_fee = $price * 100;
            if(filter_var($param['client_ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                $spbill_create_ip = $param['client_ip'];
            }
            else{
                $spbill_create_ip = "123.206.180.145";
            }
            $nonce_str = $weObj->generateNonceStr();
            $auth_code = $param['auth_code'];
            $arrdata = array(
                "deposit" => "Y",
                "appid" => $appid,
                'sub_appid' => $sub_appid,
                "mch_id" => $mch_id,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "fee_type"=>"CNY",
                "body" => $body,
                "out_trade_no" => $out_trade_no,
                "total_fee" => $total_fee,
                "spbill_create_ip" => $spbill_create_ip,
                "auth_code" => $auth_code,
                "sign_type" => "HMAC-SHA256"
//                "receipt" => $config['efp_receipt'],
//                "profit_sharing" => $config['is_profit'],
            );
            $pay_xml = $weObj->createWxPackageXml($arrdata);


//                $pay_xml = $weObj->createmicroPackageXml($appid, $sub_appid, $mch_id, $out_trade_no, $body, $sub_mch_id, $total_fee, $spbill_create_ip, $nonce_str, $auth_code);
            $url = "https://api.mch.weixin.qq.com/deposit/micropay";
            $pay_xml = $weObj->send_post($url, $pay_xml);

//            return $rarr;

            $rarr = $this->wxpay_statu($pay_xml, $sh, $out_trade_no);

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function wxpay_statu($pay_xml, $id, $orderid)
    {
        try {
            $Paylog = new Paylog();
//            return $pay_xml;
            $payinfoa = $Paylog->where(['orderid' => $orderid])->find();

            if ($payinfoa['pay_fs'] == 0 || $payinfoa['pay_fs'] == 2 || $payinfoa['pay_fs'] == 20) {
                if ($pay_xml['return_code'] == "SUCCESS") {
                    if ($pay_xml['result_code'] == "FAIL") {

                        $arrc['return_code'] = "SUCCESS";
                        if ($pay_xml['err_code'] == "USERPAYING") {
                            $arrc['result_code'] = $pay_xml['err_code'];
                        } else {
                            $arrc['result_code'] = "FAIL";
                        }
                        $arrc['return_msg'] = translate($pay_xml['err_code']);
                        $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        $arrc['out_trade_no'] = $payinfoa['orderid'];
                        $arrc['trade_no'] = $payinfoa['trade_no'];


                    } else {
                        if ($pay_xml['return_code'] && $pay_xml['result_code'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "FAIL";
                            $arrc['return_msg'] = translate($pay_xml['err_code']);
                            $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        } elseif (isset($pay_xml['trade_state']) && $pay_xml['trade_state'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            if ($pay_xml['trade_state'] == "USERPAYING") {
                                $arrc = $this->getorderinfo($orderid);
                                $arrc['result_code'] = "USERPAYING";
                                $arrc['out_trade_no'] = $payinfoa['orderid'];
                                $arrc['trade_no'] = $payinfoa['trade_no'];
                            } else {
                                $arrc['result_code'] = "FAIL";
                            }
                            $arrc['result_code'] = $pay_xml['trade_state'];
                            $arrc['return_msg'] = translate($pay_xml['trade_state']);
                            $arrc['result_msg'] = translate($pay_xml['trade_state']);
                        } else {
                            $pays['orderno'] = $pay_xml['transaction_id'];
                            $pays['pay_time'] = date('Y-m-d H:i:s', strtotime($pay_xml['time_end']));
                            $pays['pay_statu'] = 1;
                            $pays['openid'] = $pay_xml['openid'];
                            $pays['sub_openid'] = isset($pay_xml['sub_openid']) ? $pay_xml['sub_openid'] : "";
                            $pays['payinfo'] = json_encode($pay_xml);
                            $pays['price'] = $pay_xml['total_fee'] / 100;
                            $Pub = new Pub();
                            $pays['service_charge'] = $Pub->service_charge($payinfoa['mid'], $pays['price'], $payinfoa['pay_fs']);
                            $savep['orderid']=$orderid;
                            $this->deposit_creat($savep,"updata");
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            //卡券核销
//                            $Deviceobj = new Deviceobj();
//                            $s=$Deviceobj->ylb_sendvoice($orderid);
                            $TemplateMsg = new TemplateMsg();
                            $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));

                            $FeiePrint = new FeiePrint();
                            $FeiePrint->sendprint($orderid);
//                        action('index/wxauth/sendtemplate', array($id, $orderid));
                            //返回结果
                            $arrc = $this->getorderinfo($orderid);
                            $Notify=new CreateNotify();
                            $param['out_trade_no']=$orderid;
                            $param['merchantid']=$id;
                            $Notify->pay_notify($param);

                        }

                    }
                } elseif ($pay_xml['return_code'] == "FAIL") {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = translate($pay_xml['return_msg']);
                    $arrc['result_msg'] = translate($pay_xml['return_msg']);
                }
            } elseif ($payinfoa['pay_fs'] == 8) {
                if ($payinfoa['pay_statu'] == 1) {
                    $TemplateMsg = new TemplateMsg();
                    $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                    $FeiePrint = new FeiePrint();
                    $FeiePrint->sendprint($orderid);
//                    $Deviceobj = new Deviceobj();
//                    $s=$Deviceobj->ylb_sendvoice($orderid);

                    $arrc = $this->getorderinfo($orderid);
                } else {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "支付失败";
                    $arrc['result_msg'] = "支付失败";
                }
            }


        } catch (\Exception $e) {
            $arrc['return_code'] = "FAIL";
            $arrc['return_msg'] = '系统错误';
            $arrc['result_code'] = 'FAIL';
            $arrc['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $arrc;


    }


    public function wxcheckpay($param)
    {
        try {
            $orderid = $param['out_trade_no'];

            $id = $param['merchantid'];
            $payxml = $this->wxorderquery($id, $orderid);
            $rarr = $this->wxpay_statu($payxml, $id, $orderid);

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;


    }

    public function wxorderquery($id, $orderid)
    {

        try {
            $map['id'] = $id;
            $config = Db::name('Merchant')->where($map)->find();
            $agent = Db::name('agent')->where(array('id' => $config['agent']))->find();
            $users = Db::name('wx_open')->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = Db::name('wx_open')->where(array('id' => $config['wx_open_id']))->find();

            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $orderid;
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $nonce_str = $weObj->generateNonceStr();
            $arrdata = array(
                "appid" => $appid,
                "mch_id" => $mch_id,
                "sub_appid" => $sub_appid,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "out_trade_no" => $out_trade_no,
                "sign_type" => "HMAC-SHA256"
            );
            $orderxml = $weObj->createWxPackageXml($arrdata);
//            $orderxml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $url = "https://api.mch.weixin.qq.com/deposit/orderquery";
            $rarr = $weObj->send_post($url, $orderxml);

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();;
        }
        return $rarr;

    }
    private function deposit_creat($param, $type = "create")
    {
        $Deposit = new Deposit();

        $list = $Deposit->where('orderid', $param['orderid'])->find();
        if ($type == "create") {

            if (!$list) {
                $maps['status']="Y";
                $maps['room']=$param['room'];
                $maps['mid']=$param['merchantid'];
                $room = $Deposit->where($maps)->find();
                if(!$room){
                    $data['mid'] = $param['merchantid'];
                    $data['orderid'] = $param['orderid'];
                    $data['room'] = $param['room'];

                    $data['xingming'] = $param['xingming'];
                    $data['tel'] = $param['contact'];
                    $data['total_fee'] = $param['total_fee'];
                    $data['create_user'] = $param['device_id'];
                    $data['create_time'] = time();
                    $data['status'] = "N";
                    $Deposit = new Deposit();
                    $Deposit->save($data);
                }else{
                    return "error";

                }
            }
        }elseif($type == "updata"){
            if($list['status']=="N") {
                $data['status'] = "Y";
                $Deposit->save($data, ['orderid' => $param['orderid']]);
            }
        }
    }
    public function alipay($param){
        $User = new Merchant();
        $Agent = new Agent();
//        $users = $User->where(array('id' => $param['merchantid']))->find();
//        $agent = $Agent->where(array('id' => $users['agent']))->find();
//        $agent['ali_app_id']="2016080300161033";
//        $options = array(
//            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
////            'appid' => "", // 填写高级调用功能的app id
////            'rsaPrivateKey' => $agent['ali_app_key'],
//            'rsaPrivateKey' =>"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYxN0KV7Cfcoc+HDatDVB8tGpRhlgkE1I3JdRWWZj8HvT/3lWkCZ1IHZcSIFbvfi4uio7OHN0ml5U62EuEgO0A+ZgjZLgyJC3h/8XtUnLX3uLptP3Sidt87qahf7ncCSnLTC+zHL7qWBTKlAkUvRh3KtRKxd6a6oKWLT/HNnJLg1+GoSZ3y92nN3D0uQO2gDzgZ6ErJGpJLcLwMXrrQba0g58PodgwTbk9G2sChEFZuh3+TCzxm0HdcoxzJZ/p3HUhLdtvVPEuv9G+aGAAhk+yJMUw0vTsUnsWRWTbDI1jeClvIOMWj7YkwSq+Zt+SriF7WRYjwxzYnqPj+Y4Fd1zZAgMBAAECggEARJQ7ViU/WJSlObCYqt7LPvAOukJA1xEFW1RUGd9m2edbvHEmqNjYDkOaSbzSyfgu6x2wNb6nWGe7ygrG+9iUjFd/gIP6XCf5oPac94iHnXilDJz/RMA2E8NecilQWgKTDHxK/XDuE20vCDGkUfcBQJ2tZ1OkNo8HyDrP4rICZPsGlkEZtV6Ur2cTckODb2hmeyMBqe00WCQ3XBWpUHTE4ltajEylnDUVzIVSzM8dSpkYNTrbl43yMx05RTwZFg4w+VbpG/dPuJM0K6bMSuQSGgGgRy2t68EfelQdWFUOei/t3OXTdCAjzVYAm+ET+PcFplqtuIDoEi24x7Grd0q+MQKBgQDVmG2T4GLU95T2zWFN8qEx2py6FGtybLluOErDGDMyCSAsBorhTxSQ20IrlPjjlzwXu07CULoI5ukUJxAlT8J9DMzEzKzPL48L5YoMwmP/LmS7s+tPGlmkgKdjW0XOWgmzDUDQJDbCVDTnFdZOD8AzkCG5AcfSlqZdLO0PuwlmIwKBgQC3GQz5CiEST2XAEVqnXV5HPdFVus8eul/MsWIyz7J6lVG5oCfl/caXyHcQswksLkQ4vs3LXmvXLtvIif4Iu2HsCmz4iamHHCifJw1iOsEySOUnzBJzKiUDl/zSKKKpmk8Z/9QqzokOJm8dUgWNsyUTFHV1HxHf1ABTVl7aK7760wKBgQCSdBluM4SQkdHKB7iYQazVChg8XpPtuS7LrD1W19kCjc9JYJMJObfYOv5784FUS/YgL4YpJkDoqatW7hHcA3xPUd91cQFsbiee+JxXc1ItPhpDuXG2o1KjwLMFJSgP/Rx5cLToAmypgiNj700p6RLYSBNXTyk785/Oc2d4Sb6AEQKBgGxNUAQa/rbi6e+zFCk9LB/9q84G4q5tVW8xWUFu40Zo/l9LIW6ELqznMa5aCEnu0AG0suvhXO56VByJqw6lL+W7wPs+Cl3VxR1mrx70XASPY6SnrB4cxqoag7wXtyeVE8bwMSJk6mLJTx5LvuczGPHxPwzZJOx9bPfeddqc16lrAoGBAIDcIgy88mFes46wBGCu6FP5MHcVL+Vyt/CyAhaRnxuK/eu+7fw2CrTdVWoRm4WSP8F+lLttNdioA5m+EbOKypwU5fo3QQ1yhTCHEFnWixpNolBz1DOQVnJ6Nmu1ZcgZ/o4yA+fyQy4nUYIMrFwr9ZtCSeRAeQFxsZu0LN10bOi8",
//        );
//        $aliObj = new Alipayobj($options);
//        $price = $param['total_fee'];
//        $sh = $param['merchantid'];
//        $out_trade_no = $param['orderid'];
//        $body = "快捷支付";
//        $auth_code = $param['auth_code'];
//        $total_fee = $price;
//        $data['app_id'] = $agent['ali_app_id'];
//        $data['method'] = "alipay.fund.auth.order.freeze";
//        $data['charset'] = "UTF-8";
//        $data['sign_type'] = "RSA2";
//        $data['timestamp'] = date('Y-m-d H:i:s');
//        $data['version'] = "1.0";
//        $data['notify_url'] = 'http://api.wunengkeji.com';
//        $data['app_auth_token'] = $users['ali_merid'];
//        $data['biz_content'] = json_encode(array(
//            'out_trade_no' => $out_trade_no,
//            'auth_code_type' => "bar_code",
//            'out_request_no' => $out_trade_no,
//            'scene' => 'bar_code',
//            'order_title' => '酒店预授权',
//            'auth_code' => $auth_code,
//            'total_amount' => $total_fee,
//            'subject' => $body,
//            'alipay_store_id' => $users['ali_store_id'],
////                'store_id'=>I('get.id'),
//            'extend_params' => array(
//                'sys_service_provider_id' => $agent['sys_service_provider_id'],
//            ),
//        ));
//        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
//        $data['sign'] = $signContent;
//        $sj = $aliObj->scanpay($data);
//        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
//        $rarr['return_code'] = "FAIL";
//        $rarr['return_msg'] = '系统错误';
//        $rarr['result_code'] = 'FAIL';
//        $rarr['result_msg'] = json_encode($sj,true);
//        return $rarr;
//        $OfficialPay=new OfficialPay();
//        $rarr = $OfficialPay->alipay_statu($content['alipay_trade_pay_response'], $sh, $out_trade_no);
//
//        return $rarr;

    }
}